package com.tsit.study.netty.controller;

import com.tsit.study.netty.client.NettyClient;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wangxuzhi
 * @date 2020/11/25 11:53
 */
@RestController
@RequestMapping("/msg")
public class MsgSendController {

    @GetMapping("/send/{msg}")
    public Object sendMsg(@PathVariable("msg") String msg) {
        Channel channel = NettyClient.cf.channel();
        //发送请求道服务端
        FullHttpRequest request =
                new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                        HttpMethod.POST,
                        "http://127.0.0.1:6003",
                        Unpooled.wrappedBuffer(msg.getBytes()));
        request.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
        //必须设置Content length否则服务端收不到content
        request.headers().set(HttpHeaderNames.CONTENT_LENGTH, 1024);
        System.out.println(request.content().toString(CharsetUtil.UTF_8));

        channel.writeAndFlush(request);
        return null;
    }
}
